package com.weavernorth.sysap.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 公共工具类
 *
 * @author zm
 * @version V1.0 2019-11-19 created
 */
public class CommonToSapUtil {
    public static Log log = LogFactory.getLog(CommonToSapUtil.class.getName());

    /**
     * 发送post请求
     *
     * @param strUrl        路径
     * @param strRequestXml 参数(String类型)
     * @param strEncoding   编码格式
     * @return
     * @throws IOException
     */
    public String sendPost(String strUrl, String strRequestXml, String strEncoding) throws IOException {
        //基础类
        BaseBean bb = new BaseBean();

        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        try {
        HttpPost httpPost = new HttpPost(strUrl);
        //装填参数
        StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
        //log.info("请求xml=" + strRequestXml);
        //设置参数到请求对象中
        httpPost.setEntity(stringEntity);
        log.info("请求地址=" + strUrl);
        //获取用户名
        String strUsername = Util.null2String(bb.getPropValue("sapMess", "userName"));
        log.info("用户名:"+strUsername);
        //获取密码
        String strPassword = Util.null2String(bb.getPropValue("sapMess", "password"));
            log.info("密码:"+strPassword);
        //sap的接口需验证
        String strValue = "Basic " + (new BASE64Encoder().encode((strUsername + ":" + strPassword).getBytes()));
        httpPost.setHeader("Authorization", strValue);
        httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                log.info("返回结果=" + strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }
        return strBody;
    }

    /**
     * 发送post请求
     *
     * @param strUrl        路径
     * @param strRequestXml 参数(String类型)
     * @param strEncoding   编码格式
     * @param strUsername   用户名
     * @param strPassword   密码
     * @return
     * @throws IOException
     */
    public static String sendPost(String strUrl, String strRequestXml, String strEncoding,String strUsername,String strPassword) throws IOException {
        //基础类
        BaseBean bb = new BaseBean();

        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        try {
            HttpPost httpPost = new HttpPost(strUrl);
            //装填参数
            StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
            //log.info("请求xml=" + strRequestXml);
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);
            log.info("请求地址=" + strUrl);

            //sap的接口需验证
            String strValue = "Basic " + (new BASE64Encoder().encode((strUsername + ":" + strPassword).getBytes()));
            httpPost.setHeader("Authorization", strValue);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                log.info("返回结果=" + strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }
        return strBody;
    }

    /**
     * 获取当前系统的日期
     *
     * @return
     */
    public static String getCurDate() {
        //当前日期时间
        Date date = new Date(System.currentTimeMillis());
        //格式化日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //当前日期
        String strCurrentTime = dateFormat.format(date);

        return strCurrentTime;
    }

    /**
     * 获取当前系统的时间
     *
     * @return
     */
    public static String getCurTime() {
        //当前日期时间
        Date date = new Date(System.currentTimeMillis());
        //格式化时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        //返回当前时间
        String strCurrentTime = dateFormat.format(date);
        return strCurrentTime;
    }


    /**
     * 获取包含汉字的配置文件的中键的值
     *
     * @param propFileName 配置文件的名称
     * @param propKeyName  配置文件的键名
     * @return String 配置文件中对应键的值
     */
    public static String getPropInfoWithChinese(String propFileName, String propKeyName, String sysadminEncoding) {
        //返回值
        String strPropValue = "";
        BaseBean baseBean = new BaseBean();
        //编码为空,则默认为utf-8
        if (sysadminEncoding == null || "".equals(sysadminEncoding.trim())) {
            sysadminEncoding = "utf-8";
        }
        //转换编码
        try {
            strPropValue = new String(baseBean.getPropValue(propFileName, propKeyName).
                    getBytes("iso8859-1"), sysadminEncoding);

        } catch (UnsupportedEncodingException e) {
            baseBean.writeLog("获取含有汉字的配置文件的值时出错，原因：不支持的编码格式(" + sysadminEncoding + ")。"
                    + e.getMessage());
        }
        return strPropValue;
    }


}

